<template>
  <div class="score-ranking">
    <!-- 顶部筛选栏 -->
    <div class="header-filter">
      <el-card class="filter-card">
        <el-form
          ref="filterFormRef"
          :model="filterForm"
          :inline="true"
          label-width="80px"
          class="filter-form"
        >
          <el-form-item label="比赛项目">
            <el-select
              v-model="filterForm.eventId"
              placeholder="请选择比赛项目"
              clearable
              style="width: 200px"
              @change="handleEventChange"
            >
              <el-option
                v-for="event in eventOptions"
                :key="event.id"
                :label="event.name"
                :value="event.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="参赛组别">
            <el-select
              v-model="filterForm.group"
              placeholder="请选择组别"
              clearable
              style="width: 150px"
              @change="handleGroupChange"
            >
              <el-option label="男子组" value="男子组" />
              <el-option label="女子组" value="女子组" />
              <el-option label="混合组" value="混合组" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="显示排名">
            <el-select
              v-model="filterForm.topN"
              placeholder="显示前N名"
              style="width: 120px"
              @change="handleTopNChange"
            >
              <el-option label="前3名" :value="3" />
              <el-option label="前5名" :value="5" />
              <el-option label="前10名" :value="10" />
              <el-option label="前20名" :value="20" />
              <el-option label="全部" :value="0" />
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleQuery">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 统计概览 -->
    <div class="statistics-overview">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-icon gold">
                <el-icon><Trophy /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ statistics.totalEvents }}</div>
                <div class="stat-label">比赛项目</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-icon blue">
                <el-icon><User /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ statistics.totalAthletes }}</div>
                <div class="stat-label">参赛选手</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-icon green">
                <el-icon><DataAnalysis /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ statistics.totalScores }}</div>
                <div class="stat-label">成绩记录</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-icon orange">
                <el-icon><Medal /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ statistics.averageScore }}</div>
                <div class="stat-label">平均成绩</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 排名表格 -->
    <div class="ranking-table">
      <el-card class="table-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              {{ currentEventName ? `${currentEventName} - 排名统计` : '排名统计' }}
            </span>
            <div class="header-actions">
              <el-button type="success" @click="handleExportRanking">
                <el-icon><Download /></el-icon>
                导出排名
              </el-button>
              <el-button type="warning" @click="handleRecalculateRanking" :loading="recalculatingRanking">
                <el-icon><Refresh /></el-icon>
                重新计算排名
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          v-loading="loading"
          :data="rankingList"
          style="width: 100%"
          stripe
          border
          empty-text="暂无排名数据"
          :row-class-name="getRowClassName"
        >
          <el-table-column prop="ranking" label="排名" width="80" align="center">
            <template #default="{ row }">
              <div class="ranking-cell">
                <el-icon v-if="row.ranking === 1" class="medal-icon gold-medal">
                  <Trophy />
                </el-icon>
                <el-icon v-else-if="row.ranking === 2" class="medal-icon silver-medal">
                  <Trophy />
                </el-icon>
                <el-icon v-else-if="row.ranking === 3" class="medal-icon bronze-medal">
                  <Trophy />
                </el-icon>
                <span class="ranking-number">{{ row.ranking }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="athleteName" label="运动员姓名" min-width="120" show-overflow-tooltip />
          <el-table-column prop="athleteNumber" label="参赛号码" width="100" align="center" />
          <el-table-column prop="eventName" label="比赛项目" min-width="150" show-overflow-tooltip />
          <el-table-column prop="group" label="参赛组别" width="100" align="center" />
          <el-table-column prop="score" label="成绩" width="120" align="center">
            <template #default="{ row }">
              <span class="score-value" :class="getScoreClass(row.ranking)">
                {{ formatScore(row.score, row.unit) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="recordTime" label="创建时间" width="160" align="center">
            <template #default="{ row }">
              {{ formatDateTime(row.recordTime) }}
            </template>
          </el-table-column>
          <el-table-column label="奖项" width="100" align="center">
            <template #default="{ row }">
              <el-tag
                v-if="row.ranking <= 3"
                :type="getMedalTagType(row.ranking)"
                effect="dark"
              >
                {{ getMedalText(row.ranking) }}
              </el-tag>
              <span v-else class="no-medal">-</span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            :current-page="pagination.page"
            :page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 奖牌榜 -->
    <div v-if="medalStats.length > 0" class="medal-board">
      <el-card class="table-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">🏆 奖牌榜</span>
          </div>
        </template>

        <el-table
          :data="medalStats"
          style="width: 100%"
          stripe
          border
        >
          <el-table-column prop="athleteName" label="运动员" min-width="120" />
          <el-table-column label="金牌" width="80" align="center">
            <template #default="{ row }">
              <span class="medal-count gold">{{ row.goldMedals }}</span>
            </template>
          </el-table-column>
          <el-table-column label="银牌" width="80" align="center">
            <template #default="{ row }">
              <span class="medal-count silver">{{ row.silverMedals }}</span>
            </template>
          </el-table-column>
          <el-table-column label="铜牌" width="80" align="center">
            <template #default="{ row }">
              <span class="medal-count bronze">{{ row.bronzeMedals }}</span>
            </template>
          </el-table-column>
          <el-table-column label="总计" width="80" align="center">
            <template #default="{ row }">
              <span class="medal-count total">{{ row.totalMedals }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Download,
  Trophy,
  User,
  DataAnalysis,
  Medal
} from '@element-plus/icons-vue'
import { 
  getScoreList, 
  getEventList, 
  getScoreStatistics, 
  calculateRankings,
  exportScoreData 
} from '@/api/score'

// 筛选表单
const filterFormRef = ref()
const filterForm = reactive({
  eventId: '',
  group: '',
  topN: 10
})

// 列表数据
const loading = ref(false)
const recalculatingRanking = ref(false)
const rankingList = ref([])
const eventOptions = ref([])
const medalStats = ref([])

// 统计数据
const statistics = reactive({
  totalEvents: 0,
  totalAthletes: 0,
  totalScores: 0,
  averageScore: '0'
})

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 当前选中的项目名称
const currentEventName = computed(() => {
  const event = eventOptions.value.find(e => e.id === filterForm.eventId)
  return event ? event.name : ''
})

// 查询排名
const handleQuery = async () => {
  pagination.page = 1
  await loadRankingList()
}

// 重置筛选
const handleReset = () => {
  filterFormRef.value?.resetFields()
  handleQuery()
}

// 项目变化
const handleEventChange = () => {
  loadRankingList()
  loadMedalStats()
}

// 组别变化
const handleGroupChange = () => {
  loadRankingList()
}

// 显示排名变化
const handleTopNChange = () => {
  loadRankingList()
}

// 加载排名列表
const loadRankingList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      size: filterForm.topN > 0 ? filterForm.topN : pagination.size,
      eventId: filterForm.eventId,
      group: filterForm.group,
      orderBy: 'ranking',
      orderDirection: 'asc'
    }
    
    const response = await getScoreList(params)
    rankingList.value = response.data.records || []
    
    if (filterForm.topN === 0) {
      pagination.total = response.data.total || 0
    } else {
      pagination.total = Math.min(response.data.total || 0, filterForm.topN)
    }
  } catch (error) {
    console.error('加载排名列表失败:', error)
    ElMessage.error('加载排名列表失败')
  } finally {
    loading.value = false
  }
}

// 加载比赛项目选项
const loadEventOptions = async () => {
  try {
    const response = await getEventList({ status: 1 })
    eventOptions.value = response.data || []
  } catch (error) {
    console.error('加载比赛项目失败:', error)
  }
}

// 加载统计数据
const loadStatistics = async () => {
  try {
    const params = {
      eventId: filterForm.eventId,
      group: filterForm.group
    }
    const response = await getScoreStatistics(params)
    Object.assign(statistics, response.data || {})
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 加载奖牌统计
const loadMedalStats = async () => {
  try {
    const params = {
      eventId: filterForm.eventId,
      group: filterForm.group,
      medalOnly: true
    }
    const response = await getScoreList(params)
    const scores = response.data.records || []
    
    // 计算奖牌统计
    const athleteMap = new Map()
    
    scores.forEach(score => {
      if (score.ranking <= 3) {
        const athleteId = score.athleteId
        if (!athleteMap.has(athleteId)) {
          athleteMap.set(athleteId, {
            athleteName: score.athleteName,
            goldMedals: 0,
            silverMedals: 0,
            bronzeMedals: 0,
            totalMedals: 0
          })
        }
        
        const athlete = athleteMap.get(athleteId)
        if (score.ranking === 1) athlete.goldMedals++
        else if (score.ranking === 2) athlete.silverMedals++
        else if (score.ranking === 3) athlete.bronzeMedals++
        athlete.totalMedals++
      }
    })
    
    medalStats.value = Array.from(athleteMap.values())
      .sort((a, b) => {
        // 按金牌数、银牌数、铜牌数排序
        if (a.goldMedals !== b.goldMedals) return b.goldMedals - a.goldMedals
        if (a.silverMedals !== b.silverMedals) return b.silverMedals - a.silverMedals
        return b.bronzeMedals - a.bronzeMedals
      })
  } catch (error) {
    console.error('加载奖牌统计失败:', error)
  }
}

// 重新计算排名
const handleRecalculateRanking = async () => {
  if (!filterForm.eventId) {
    ElMessage.warning('请先选择比赛项目')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      '重新计算排名将根据最新成绩重新生成排名信息，确定继续吗？',
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    recalculatingRanking.value = true
    await calculateRankings(filterForm.eventId, { group: filterForm.group })
    ElMessage.success('排名计算完成')
    await loadRankingList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重新计算排名失败:', error)
      ElMessage.error('重新计算排名失败')
    }
  } finally {
    recalculatingRanking.value = false
  }
}

// 导出排名
const handleExportRanking = async () => {
  try {
    const params = {
      eventId: filterForm.eventId,
      group: filterForm.group,
      topN: filterForm.topN,
      type: 'ranking'
    }
    await exportScoreData(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadRankingList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.page = page
  loadRankingList()
}

// 获取行类名
const getRowClassName = ({ row }) => {
  if (row.ranking === 1) return 'gold-row'
  if (row.ranking === 2) return 'silver-row'
  if (row.ranking === 3) return 'bronze-row'
  return ''
}

// 获取成绩样式类
const getScoreClass = (ranking) => {
  if (ranking === 1) return 'gold-score'
  if (ranking === 2) return 'silver-score'
  if (ranking === 3) return 'bronze-score'
  return ''
}

// 获取奖牌标签类型
const getMedalTagType = (ranking) => {
  const typeMap = {
    1: 'warning',  // 金牌
    2: 'info',     // 银牌
    3: 'success'   // 铜牌
  }
  return typeMap[ranking] || ''
}

// 获取奖牌文本
const getMedalText = (ranking) => {
  const textMap = {
    1: '金牌',
    2: '银牌',
    3: '铜牌'
  }
  return textMap[ranking] || ''
}

// 格式化成绩
const formatScore = (score, unit) => {
  if (!score) return '-'
  return `${score}${unit || ''}`
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 组件挂载时加载数据
onMounted(() => {
  loadEventOptions()
  loadRankingList()
  loadStatistics()
  loadMedalStats()
})
</script>

<style scoped>
.score-ranking {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 120px);
}

.header-filter {
  margin-bottom: 20px;
}

.filter-card {
  background-color: #fff;
}

.filter-form {
  margin-bottom: 0;
}

.filter-form .el-form-item {
  margin-bottom: 0;
}

.statistics-overview {
  margin-bottom: 20px;
}

.stat-card {
  background-color: #fff;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: #fff;
}

.stat-icon.gold {
  background: linear-gradient(135deg, #FFD700, #FFA500);
}

.stat-icon.blue {
  background: linear-gradient(135deg, #409EFF, #67C23A);
}

.stat-icon.green {
  background: linear-gradient(135deg, #67C23A, #85CE61);
}

.stat-icon.orange {
  background: linear-gradient(135deg, #E6A23C, #F56C6C);
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.ranking-table,
.medal-board {
  margin-bottom: 20px;
}

.table-card {
  background-color: #fff;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.ranking-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.medal-icon {
  font-size: 18px;
}

.gold-medal {
  color: #FFD700;
}

.silver-medal {
  color: #C0C0C0;
}

.bronze-medal {
  color: #CD7F32;
}

.ranking-number {
  font-weight: 600;
  font-size: 16px;
}

.score-value {
  font-weight: 600;
  font-size: 16px;
}

.gold-score {
  color: #FFD700;
}

.silver-score {
  color: #C0C0C0;
}

.bronze-score {
  color: #CD7F32;
}

.no-medal {
  color: #909399;
}

.medal-count {
  font-weight: 600;
  font-size: 16px;
}

.medal-count.gold {
  color: #FFD700;
}

.medal-count.silver {
  color: #C0C0C0;
}

.medal-count.bronze {
  color: #CD7F32;
}

.medal-count.total {
  color: #409EFF;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table .gold-row) {
  background-color: rgba(255, 215, 0, 0.1);
}

:deep(.el-table .silver-row) {
  background-color: rgba(192, 192, 192, 0.1);
}

:deep(.el-table .bronze-row) {
  background-color: rgba(205, 127, 50, 0.1);
}

:deep(.el-pagination) {
  justify-content: center;
}
</style>
